import router from "@/router";
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, CreateAxiosDefaults } from "axios";
// const serve = axios.create({
//     baseURL:'/api'
// })

interface IResult <T=any>{
    code?:0|1,
    msg:string,
    total?:number,
    data:T,
   
}

class MyAxios { 
    serve: AxiosInstance
    // 默认的配置
    baseConfig: CreateAxiosDefaults = { baseURL: import.meta.env.VITE_API_URL, timeout: 6000 }
    // 用户new的时候传入的配置
    constructor(config:CreateAxiosDefaults) { 
      this.serve = axios.create({...this.baseConfig, ...config})
      // 定义拦截器
      this.serve.interceptors.request.use(config=>{
        const token = localStorage.getItem('token')
        if (token) {
          config.headers.authorization = token
        }
        return config
      })
      this.serve.interceptors.response.use(res=>{
        return res
      },err=>{
        if (err.response?.status === 401) {
          router.push('/login')
        }
      })

    }
    // 重写 axios get  post put 。。。
    public get<T>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<IResult<T>, any>> { 
      return this.serve.get(url, config)
    }
    public post<T>(url: string, data: Object = {}): Promise<AxiosResponse<IResult<T>, any>> { 
        return this.serve.post(url, data)
      }

}

// export const mockAxios = new MyAxios({baseURL:'/'})
export default new MyAxios({})
